import json
import os
from PyQt5.QtCore import QByteArray
from typing import Dict, Any
from rss_reader import CONFIG_FILE_PATH
from rss_reader.logger import logger


class JsonSettings:
    def __init__(self, config_path=CONFIG_FILE_PATH):
        self.config_path = config_path
        self.default_setting =  {
            "window": {},
            "splitter": {},
            "treeview": {},
            "mark_read_delay":5,
            "layout": "Horizontal"   # 水平三栏
        }
        self.settings = self._load_settings()

    def _load_settings(self) -> Dict[str, Any]:
        """加载JSON配置文件"""
        with open(self.config_path, 'r', encoding='utf-8') as f:
            try:
                loaded_setting = json.load(f)
                setting = {**self.default_setting, **loaded_setting}
                return setting
            except Exception as e:
                logger.error(f"读取配置失败: {str(e)}")
                return self.default_setting

    def save(self):
        """保存配置到文件"""
        os.makedirs(os.path.dirname(self.config_path), exist_ok=True)
        with open(self.config_path, 'w', encoding='utf-8') as f:
            json.dump(self.settings, f, indent=4)

    def set_value(self, key: str, value: Any):
        """设置值（支持点分隔路径如 'treeview.header.state'）"""
        keys = key.split('.')
        current = self.settings
        for k in keys[:-1]:
            current = current.setdefault(k, {})
        current[keys[-1]] = value
        self.save()

    def get_value(self, key: str, default=None) -> Any:
        """获取值"""
        keys = key.split('.')
        current = self.settings
        for k in keys:
            if k not in current:
                return default
            current = current[k]
        return current

    # 专门处理Qt二进制数据
    def set_bytearray(self, key: str, data: QByteArray):
        self.set_value(key, data.toHex().data().decode())

    def get_bytearray(self, key: str) -> QByteArray:
        hex_str = self.get_value(key, "")
        return QByteArray.fromHex(hex_str.encode()) if hex_str else QByteArray()